#include <iostream>
#include <fstream>
#include "contacts.pb.h"

using namespace std;
using namespace c_contacts;
using namespace google::protobuf;

/**
 * 打印联系⼈列表
 */
void PrintfContacts(const Contacts &contacts)
{
    for (int i = 0; i < contacts.contacts_size(); ++i)
    {
        const PeopleInfo &people = contacts.contacts(i);
        cout << "------------联系人" << i + 1 << "------------" << endl;
        cout << "姓名：" << people.name() << endl;
        cout << "年龄：" << people.age() << endl;
        int j = 1;
        for (const PeopleInfo_Phone &phone : people.phone()){
            cout << "电话" << j++ << ": " << phone.number() << endl;
        }

        // 获取到 reflection 对象
        const Reflection* reflection = PeopleInfo::GetReflection();
        // 通过 reflection 获取未知字段集合
        const UnknownFieldSet& set = reflection->GetUnknownFields(people);
        // 遍历集合
        for(int j = 0; j < set.field_count(); ++j){
            // 获取到单个未知字段
            const UnknownField& unknown_field = set.field(j);
            std::cout << "未知字段: " << j + 1 << ": " << ", 编号：" << unknown_field.number() ;
            switch (unknown_field.type()){
            case UnknownField::Type::TYPE_VARINT:
                std::cout << ", 值: " << unknown_field.varint() << std::endl;
                break;
            case UnknownField::Type::TYPE_LENGTH_DELIMITED:
                std::cout << ", 值: " << unknown_field.length_delimited() << std::endl;
                break;
            default:
                break;
            }
        }
    }
}

int main(){
    // 读取 contacts
    Contacts contacts;
    fstream input("../contacts.bin", ios::in | ios::binary);
    if (!contacts.ParseFromIstream(&input)){
        cerr << "Failed to parse contacts." << endl;
        input.close();
        return -1;
    }

    // 打印 contacts
    PrintfContacts(contacts);
    input.close();

    return 0;
}
